<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <el-tabs v-model="activeName" @tab-click="tabClick" class="mar-t--10">
        <!-- 快递公司 -->
        <el-tab-pane label="快递公司" name="delivery">
          <div class="bg-color-white">
            <div>
              <el-button @click="showAddSysExpress" type="primary">快速添加</el-button>
              <el-button @click="showSaveExpress()" type="primary">自定义添加</el-button>
              <el-button style="margin-left: 10px" @click="setDefaultExpressOutlets()">设置默认网点</el-button>
            </div>
            <!--顶部搜索 -->
            <div class="top-operate-default mar-t-20">
              <div class="search-item">
                <label>搜索快递：</label>
                <el-select v-model="express.textCol">
                  <el-option label="快递名称" value="expressName"></el-option>
                  <el-option label="快递公司编码" value="expressCode"></el-option>
                </el-select>
                <el-input v-model="express.textValue" style="width:200px" placeholder="请输入内容"></el-input>
                <label class="mar-l-20">快递类型：</label>
                <el-select v-model="express.expressType" placeholder="快递类型" class="pad-l-10">
                  <el-option label="全部" value="" />
                  <el-option v-for="(val, key) in dict.expressType" :key="key" :label="val" :value="key"/>
                </el-select>
                <label class="mar-l-20">快递状态：</label>
                <el-select v-model="express.expressStatus" placeholder="快递状态" class="pad-l-10">
                  <el-option label="全部" value="" />
                  <el-option v-for="(val, key) in dict.expressStatus" :key="key" :label="val" :value="key"/>
                </el-select>
                <el-button-group class="mar-l-20">
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="resetSearch">重置</el-button>
                </el-button-group>
              </div>
            </div>
            <!-- 全选、操作 -->
            <div>
              <div class="pad-t-15 pad-b-15 font-14 v-align-c">
                <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-20">当页全选</span></el-checkbox>
                <span class="pad-l-4 pad-r-4">|</span>
                <div class="width-80">已选{{multipleSelection.length}}项</div>
                <el-button class="batch-btn" @click.native="batchEnableExpress">批量启用</el-button>
                <el-button class="batch-btn" @click.native="batchDisableExpress">批量停用</el-button>
                <el-button class="batch-btn" @click.native="batchDeleteExpress">批量删除</el-button>
              </div>
            </div>
            <!-- 内容列表 -->
            <div class="table-container">
              <el-table  ref="multipleTable" :data="expressList" v-loading="listLoading"
                  element-loading-text="加载中" style="width: 100%" @selection-change="handleSelectionChange"
                  header-cell-class-name="default-header" row-class-name="default-row">
                <el-table-column width="50px" type="selection"></el-table-column>
                <el-table-column width="200px" label="类型" prop="expressType">
                  <template slot-scope="scope">
                    <div>{{dict.expressType[scope.row.expressType]}}</div>
                  </template>
                </el-table-column>
                <el-table-column width="200px" label="快递名称" prop="expressName" fixed="left"></el-table-column>
                <el-table-column width="200px" label="快递公司编码" prop="expressCode" fixed="left"></el-table-column>
                <el-table-column width="180px" label="状态" prop="expressStatus">
                  <template slot-scope="scope">
                    <div>{{dict.expressStatus[scope.row.expressStatus]}}</div>
                  </template>
                </el-table-column>
                <el-table-column min-width="200px" label="操作" align="right" fixed="right">
                  <template slot-scope="scope">
                    <el-button type="text" size="medium" @click="showSaveExpress(scope.row)">编辑</el-button>
                    <el-button type="text" size="medium" v-if="scope.row.expressStatus == 1" @click="disableExpress(scope.row)">停用</el-button>
                    <el-button type="text" size="medium" v-if="scope.row.expressStatus == 0" @click="enableExpress(scope.row)">启用</el-button>
                    <el-button type="text" size="medium" v-if="scope.row.expressStatus == 0" @click="deleteExpress(scope.row)">删除</el-button>
                    <el-button type="text" size="medium" @click="addStandardFaceSheet(scope.row)">设置标准面单模板</el-button>
                    <!-- <el-button type="text" size="medium" v-if="scope.row.expressCode == 'JD'" @click="editKdnConfig(scope.row)">快递鸟参数</el-button> -->
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 列表分页 -->
            <div class="pagination">
              <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="searchListQuery.currentPage"
                            :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
              </el-pagination>
            </div>

            <el-dialog title="添加快递" :visible.sync="addSysExpressVisible" :close-on-press-escape="true" width="850px">
              <div class="pad-30">
                <div class="top-operate">
                  <div>
                    <div>
                      <el-input style="width: 200px" v-model="dialogQuery.expressName" placeholder="请输入快递名称"></el-input>
                      <el-button type="primary" plain @click="handleDialogSearch">查询</el-button>
                      <el-button plain="" @click="batchAddExpress">批量添加</el-button>
                    </div>
                  </div>
                </div>
                <!-- 内容列表 -->
                <div class="table-container">
                  <el-table :data="systemExpressList" style="width: 100%" @selection-change="handleDialogSelectionChange" >
                    <el-table-column width="55px" type="selection" align="center"></el-table-column>
                    <el-table-column width="200px" label="类型" prop="expressType">
                      <template slot-scope="scope">
                        <div>{{dict.expressType[scope.row.expressType]}}</div>
                      </template>
                    </el-table-column>
                    <el-table-column width="250px" label="快递名称" prop="expressName"></el-table-column>
                    <el-table-column width="180px" label="快递公司编码" prop="expressCode"></el-table-column>
                    <el-table-column min-width="100px" label="操作">
                      <template slot-scope="scope">
                        <el-button type="primary" @click="addSysExpress(scope.row)">选择</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="pagination">
                    <el-pagination background @size-change="handleDialogSizeChange" @current-change="handleDialogCurrentChange"
                                  :current-page="dialogQuery.currentPage"
                                  :page-sizes="[10, 20, 50, 100]" :page-size="dialogQuery.size"
                                  layout="total, sizes, prev, pager, next, jumper"
                                  :total="dialogQuery.total">
                    </el-pagination>
                  </div>
                </div>
              </div>
            </el-dialog>
            <el-dialog title="自定义快递公司" :visible.sync="addSysCustomVisible" :close-on-press-escape="true" width="800px">
              <el-form :model="dialogExpress" label-position="right" label-width="100px" :rules="rules" ref="dialogExpress" class="pad-30">
                <el-form-item label="快递名称" prop="expressName">
                  <div><el-input v-model="dialogExpress.expressName" placeholder="请输入快递公司名称， 1-10字" max="10"></el-input></div>
                </el-form-item>
                <el-form-item label="快递编码" prop="expressCode">
                  <div>
                    <el-input v-model="dialogExpress.expressCode" placeholder="请输入快递公司编码， 1-10字" max="10"></el-input>
                    <span class="font-12">若快递编码不匹配，对接快递物流信息或对接快递鸟面单将会失败，请谨慎设置或修改快递编码</span>
                  </div>
                </el-form-item>
                <el-form-item label="快递类型" prop="expressType">
                  <div>
                    <el-select v-model="dialogExpress.expressType" placeholder="请选择快递类型" >
                      <el-option v-for="(val, key) in dict.expressType" :key="key" :label="val" :value="key"/>
                    </el-select>
                  </div>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="addSysCustomVisible = false">取消</el-button>
                <el-button type="primary" @click="saveExpress">确定</el-button>
              </div>
            </el-dialog>
            <el-dialog title="设置标准面单模板" :visible.sync="addStandardFaceSheetVisible" :close-on-press-escape="true" width="800px">
              <el-form :model="faceSheetEntity" label-position="right" label-width="150px" :rules="rules" ref="faceSheetEntity" class="pad-30">
                <el-form-item label="抖音面单模板">
                  <div>
                    <el-select v-model="faceSheetEntity.douYinStandardTemplateId" placeholder="请选择抖音标准模板" @change="handleTemplateChange(faceSheetEntity.douYinStandardTemplateId,1)">
                      <el-option v-for="(item, index) in douYinStandardList" :key="index" :label="item.templateName" :value="item.expressStandardFaceSheetTemplateId"/>
                    </el-select>
                    <el-select v-model="faceSheetEntity.douYincCustomTemplateId" placeholder="请选择抖音自定义模板" clearable>
                      <el-option v-for="(item, index) in douYinCustomList" :key="index" :label="item.templateName" :value="item.expressStandardFaceSheetTemplateId"/>
                    </el-select>
                  </div>
                </el-form-item>
                <el-form-item label="拼多多面单模板">
                  <div>
                    <el-select v-model="faceSheetEntity.pinDuoDuoStandardTemplateId" placeholder="请选择拼多多模板" @change="handleTemplateChange(faceSheetEntity.pinDuoDuoStandardTemplateId,4)">
                      <el-option v-for="(item, index) in pinDuoDuoStandardList" :key="index" :label="item.templateName" :value="item.expressStandardFaceSheetTemplateId"/>
                    </el-select>
                    <el-select v-model="faceSheetEntity.pinDuoDuoCustomTemplateId" placeholder="请选择拼多多自定义模板" clearable>
                      <el-option v-for="(item, index) in pinDuoDuoCustomList" :key="index" :label="item.templateName" :value="item.expressStandardFaceSheetTemplateId"/>
                    </el-select>
                  </div>
                </el-form-item>
                <el-form-item label="淘宝菜鸟面单模板">
                  <div>
                    <el-select v-model="faceSheetEntity.taoBaoStandardTemplateId" placeholder="请选择淘宝模板" @change="handleTemplateChange(faceSheetEntity.taoBaoStandardTemplateId,3)">
                      <el-option v-for="(item, index) in taoBaoStandardList" :key="index" :label="item.templateName" :value="item.expressStandardFaceSheetTemplateId"/>
                    </el-select>
                    <el-select v-model="faceSheetEntity.taoBaoCustomTemplateId" placeholder="请选择淘宝自定义模板" clearable>
                      <el-option v-for="(item, index) in taoBaoCustomList" :key="index" :label="item.templateName" :value="item.expressStandardFaceSheetTemplateId"/>
                    </el-select>
                  </div>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="addStandardFaceSheetVisible = false">取消</el-button>
                <el-button type="primary" @click="saveStandardFaceSheet">确定</el-button>
              </div>
            </el-dialog>
            <!-- 设置默认网点dialog -->
            <el-dialog title="设置默认网点" :visible.sync="defaultExpressOutletsVisible" :close-on-press-escape="true" width="800px">
              <defaultExpressOutlets :showFlag="defaultExpressOutletsVisible"></defaultExpressOutlets>
            </el-dialog>
            <el-dialog title="快递鸟参数" :visible.sync="kdnConfigVisible" :close-on-press-escape="true" width="800px">
              <el-form :model="kdnConfigForm" label-position="right" label-width="100px" ref="kdnConfigForm" class="pad-30">
                <el-form-item label="发货仓编码" prop="warehouseId">
                  <div><el-input v-model="kdnConfigForm.warehouseId" placeholder="请输入发货仓编码,1-30字" max="30"></el-input></div>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="kdnConfigVisible = false">取消</el-button>
                <el-button type="primary" @click="saveKdnConfig">确定</el-button>
              </div>
            </el-dialog>
          </div>
        </el-tab-pane>
        <!-- 运费模版 -->
        <el-tab-pane v-if="getEnterpriseConfig().deliveryTemplateAuthority == 1 && !supplierId" label="运费模版" name="deliveryTemplate">
          <div class="bg-color-white pad-20">
            <!-- 添加运费模版按钮 -->
            <div>
              <el-button type="primary" @click="$router.push('/order/order/express/delivery-template-detail/index')">添加运费模版</el-button>
            </div>
            <div>
              <div v-for="(template, index) in deliveryTemplateList" :key="index" >
                <div class="universal-template pad-5 pad-l-0 mar-t-20">
                  <span class="font-16" style="border-bottom:3px solid #409EFF;color:#409EFF;font-weight:700">{{template.templateName}}</span>
                </div>
                <div class="mar-t-10">
                  <template>
                    <el-table :data="template.templateDetailsList" align="center" style="width: 100%">
                      <el-table-column :key="Math.random()" align="center" prop="areaNames" label="配送区域" :width="firstTdWidth"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 1" align="center" prop="startItemStandard" :label="'首件(件)'"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 1" align="center" prop="startItemFee" label="运费(元)"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 1" align="center" prop="addItemStandard" :label="'续件(件)'"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 1" align="center" prop="addItemFee" label="续费(元)"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 2" align="center" prop="startWeightStandard" :label="'首件(kg)'"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 2" align="center" prop="startWeightFee" label="运费(元)"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 2" align="center" prop="addWeightStandard" :label="'续件(kg)'"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 2" align="center" prop="addWeightFee" label="续费(元)"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 3" align="center" prop="startVolumeStandard" :label="'首件(立方米)'"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 3" align="center" prop="startVolumeFee" label="运费(元)"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 3" align="center" prop="addVolumeStandard" :label="'续件(立方米)'"></el-table-column>
                      <el-table-column :key="Math.random()" v-if="template.feeType == 3" align="center" prop="addVolumeFee" label="续费(元)"></el-table-column>
                  </el-table>
                  </template>
                  <div class="flex v-align-c" style="background:#F9FAFC">
                    <div :style="{'width':firstTdWidth+'px','font-weight':'700','text-align':'center'}">{{template.templateType==1?'快递模板':'物流模版'}}</div>
                    <div style="flex:1;text-align:right" class="pad-r-20">
                      <el-button type="text" @click.native="showDeliveryTemplate(template)">编辑</el-button>
                      <el-button type="text" @click="copyDeliveryTemplate(template)">复制</el-button>
                      <el-button type="text" @click="deleteTemplate(template)">删除</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <!-- 物流参数 -->
        <el-tab-pane v-if="enterpriseConfig.wholesaleAuthority == 1 && getEnterpriseConfig().deliveryTemplateAuthority == 1 && !supplierId" label="物流参数" name="logistics">
          <div class="bg-color-white pad-20">
            <el-form label-width="150px" class="mar-t-20">
              <el-form-item label="不上门区域过滤条件:">
                <p>当使用物流配送，可设置物流点不送货上门的区域过滤关键字，使用逗号（,）隔开。</p>
                <el-input type="textarea" style="width:500px" v-model="expressConfig.homeAreaFilter"></el-input>
              </el-form-item>
              <el-form-item>
                <p>当订单的物流费低于最低费用时，按最低费用收取。</p>
                <el-input style="width:500px" v-model="expressConfig.minLogisticsFee" @keyup.native="expressConfig.minLogisticsFee = checkInputNum(expressConfig.minLogisticsFee)" maxlength="10"><template slot="append">元</template></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveEnterpriseExpressConfig">保存</el-button>
              </el-form-item>
            </el-form>
            <hr>
            <div>
              <div class="mar-t-20 mar-b-20">
                <el-button type="primary" @click="addHomeFee()">添加上门费用</el-button>
              </div>
              <div>
                <el-table :data="homeFeeList">
                  <el-table-column label="序号" prop="sortNo">
                    <template slot-scope="scope">
                      {{scope.row.sortNo * 1 + 1}}
                    </template>
                  </el-table-column>
                  <el-table-column label="商品数量区间(件)">
                    <template slot-scope="scope">
                      {{scope.row.rangeMin}} - {{scope.row.rangeMax}}
                    </template>
                  </el-table-column>
                  <el-table-column label="费用(元)" prop="homeFee"></el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button type="text" size="medium" @click="editHomeFee(scope.$index == (homeFeeList.length - 1), scope.row)">编辑</el-button>
                      <el-button v-if="homeFeeList && scope.$index == (homeFeeList.length - 1)" type="text" size="medium" @click="deleteHomeFee(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
          <!-- 添加/编辑仓库 弹窗 -->
          <el-dialog title="" :visible.sync="homeFeeVisible" width="32%">
            <el-form label-width="150px">
              <el-form-item label="商品数量区间">
                <el-input style="width:25%" v-model="homeFeeTemp.rangeMin" :disabled="true"></el-input>
                <span>-</span>
                <el-input style="width:25%" v-model="homeFeeTemp.rangeMax" :disabled="homeFeeTemp.disableRangeMax" @keyup.native="homeFeeTemp.rangeMax = checkInputPositiveNum(homeFeeTemp.rangeMax)"></el-input>
                <span>件</span>
              </el-form-item>
              <el-form-item label="物流上门费用">
                <el-input style="width:55%" v-model="homeFeeTemp.homeFee" @keyup.native="homeFeeTemp.homeFee = checkInputNum(homeFeeTemp.homeFee)"></el-input>
                <span>元</span>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="homeFeeVisible = false">取 消</el-button>
              <el-button type="primary" @click="onSaveHomeFee">确 定</el-button>
            </span>
          </el-dialog>
        </el-tab-pane>
        <!-- 电子面单 -->
        <el-tab-pane label="电子面单" name="electronicFaceSheet"></el-tab-pane>
        <el-tab-pane label="快递面单模板" name="template"></el-tab-pane>
      </el-tabs>
    </div>
      <template v-if="activeName === 'template'">
        <face-sheet-template :villageSupplierConfig="villageSupplierConfig"></face-sheet-template>
      </template>
      <template v-if="activeName === 'electronicFaceSheet'">
        <electronic-face-sheet :villageSupplierConfig="villageSupplierConfig"></electronic-face-sheet>
      </template>
  </div>
</template>

<style lang="less" scoped>
  .tips {
    color: red;
    font-size: large;
  }
</style>

<script>
  import defaultExpressOutlets from './components/default-express-outlets'
  import faceSheetTemplate from './face-sheet-template'
  import electronicFaceSheet from './electronic-face-sheet'
  import { pageExpress, pageSystemExpress, saveExpress, saveSysExpress, batchEnableExpress,
    batchDisableExpress, batchDeleteExpress, getEnterpriseExpressConfig, saveEnterpriseExpressConfig,
    saveStandardFaceSheet } from '@/api/goods/express'
  import { listTemplate, copyDeliveryTemplate, deleteTemplate } from '@/api/sell/delivery-template'
  import { saveHomeFee, deleteHomeFee, listHomeFee } from '@/api/user/homeFee'
  import { listProvince, listCity, listDistrict } from '@/api/area/area'
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import thirdAuth from '../../../shop/components/third-auth'
  import { getPlatformTemplateList, getCustomTemplateListById } from '@/api/user/expressFaceSheetTemplate'
  import { getVillageSupplier } from '@/api/user/supplier'
  import { getKdnConfig, saveKdnConfig } from '@/api/user/expressKdnConfig'
  export default {
    components: { faceSheetTemplate, electronicFaceSheet, defaultExpressOutlets },
    mixins: [thirdAuth],
    data() {
      return {
        total: 0,
        listLoading: false,
        searchListQuery: {},
        defaultQuery: {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10
        },
        express: {
          textCol: 'expressName',
          textValue: '',
          expressStatus: '',
          expressType: ''
        },
        dict: {
          payType: {},
          expressType: {},
          expressStatus: {},
          electronicSheetFlag: {}
        },
        expressList: [],
        provinceList: [],
        cityList: [],
        districtList: [],
        systemExpressList: [],
        multipleSelection: [],
        multipleExpressOutletsSelection: [],
        dialogMultipleSelection: [],
        dialogQuery: {
          expressName: '',
          currentPage: 1,
          size: 10,
          total: 0
        },
        addSysExpressVisible: false,
        addSysCustomVisible: false,
        addStandardFaceSheetVisible: false,
        sheetConfigVisible: false,
        defaultExpressOutletsVisible: false,
        rules: {
          expressName: [
            { required: true, message: '请填写快递名称', trigger: 'blur' }
          ],
          expressCode: [
            { required: true, message: '请填写快递编码', trigger: 'blur' }
          ],
          expressType: [
            { required: true, message: '请选择快递类型', trigger: 'change' }
          ]
        },
        allChecked: false,
        allExpressOutletsChecked: false,
        activeName: 'delivery',
        firstTdWidth: 600,
        homeFeeVisible: false,
        deliveryTemplateList: [],
        homeFeeList: [],
        homeFee: {
          enterpriseId: '',
          sortNo: '',
          rangeMin: '',
          rangeMax: '',
          homeFee: ''
        },
        homeFeeTemp: {
          enterpriseId: '',
          sortNo: '',
          rangeMin: '',
          rangeMax: '',
          homeFee: ''
        },
        enterpriseConfig: {},
        dialogExpress: {
          expressName: '',
          expressCode: '',
          expressType: ''
        },
        // 标准面单模板实体
        faceSheetEntity: {
          enterpriseExpressId: '',
          douYinStandardTemplateId: '',
          douYinCustomTemplateId: '',
          pinDuoDuoStandardTemplateId: '',
          pinDuoDuoCustomTemplateId: '',
          taoBaoStandardTemplateId: '',
          taoBaoCustomTemplateId: ''
        },
        expressConfig: {
          enterpriseId: this.getEnterpriseId(),
          homeAreaFilter: '',
          minLogisticsFee: ''
        },
        douYinStandardList: [],
        douYinCustomList: [],
        pinDuoDuoStandardList: [],
        pinDuoDuoCustomList: [],
        taoBaoStandardList: [],
        taoBaoCustomList: [],
        isOpen: false,
        supplierId: this.getSupplierId(),
        // 供应商
        villageSupplierConfig: {},
        // 快递鸟参数
        kdnConfigVisible: false,
        kdnConfigForm: {
          enterpriseExpressId: '',
          warehouseId: ''
        }
      }
    },
    // 初始化页面
    created() {
      this.searchListQuery = { ...this.defaultQuery }
      this.activeName = this.getCurrentPage().query.activeName || 'delivery'
      listProvince().then(response => {
        if (response.isError) return
        this.provinceList = response.data
      })
      this.getEnterpriseExpressConfig()
      getByEnterpriseId(this.getEnterpriseId()).then(response => {
        if (response.isError) return
        this.enterpriseConfig = response.data
      })
      this.init()
    },
    mounted() {
      this.initBaseData()
    },
    methods: {
      initBaseData() {
        if (this.getSupplierId()) {
          getVillageSupplier(this.getSupplierId()).then(response => {
            if (response.isError) return
            this.villageSupplierConfig = response.data
          })
        }
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.init()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.init()
      },
      setSearchListQuery() {
        // 搜索状态
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.size = size
        this.searchListQuery.expressType = this.express.expressType
        this.searchListQuery.expressStatus = this.express.expressStatus
        this.searchListQuery.supplierId = this.getSupplierId()
        this.searchListQuery[this.express.textCol] = this.express.textValue
      },
      init() {
        if (this.activeName === 'delivery') {
          this.setSearchListQuery()
          this.listLoading = true
          pageExpress(this.searchListQuery).then(response => {
            if (response.isError) {
              return
            }
            this.total = response.data.total
            this.expressList = response.data.records
            this.dict = response.data.dict
            this.listLoading = false
          })
        }
        if (this.activeName === 'deliveryTemplate') {
          this.listTemplate()
        }
        if (this.activeName === 'logistics') {
          this.listHomeFee()
        }
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      resetSearch() {
        this.searchListQuery = { ... this.defaultQuery }
        this.express = {
          textCol: 'expressName',
          textValue: ''
        }
        this.init()
      },
      handleDialogSearch() {
        this.dialogQuery.currentPage = 1
        this.searchEls()
      },
      searchEls() {
        pageSystemExpress({
          enterpriseId: this.getEnterpriseId(),
          currentPage: this.dialogQuery.currentPage,
          size: this.dialogQuery.size,
          expressName: this.dialogQuery.expressName,
          supplierId: this.getSupplierId()
        }).then(response => {
          if (response.isError) return
          this.dialogQuery.total = response.data.total
          this.systemExpressList = response.data.records
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.expressList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      handleDialogSelectionChange(val) {
        this.dialogMultipleSelection = val
      },
      handleDialogSizeChange(val) {
        this.dialogQuery.size = val
        this.searchEls()
      },
      handleDialogCurrentChange(val) {
        this.dialogQuery.currentPage = val
        this.searchEls()
      },
      showAddSysExpress() {
        this.addSysExpressVisible = true
        this.searchEls()
      },
      showSaveExpress(row) {
        this.addSysCustomVisible = true
        if (row) {
          Object.assign(this.dialogExpress, row)
        }
        this.dialogExpress.expressType = this.dialogExpress.expressType.toString()
      },
      enableExpress(row) {
        row.expressStatus = 1
        saveExpress(row).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功！' })
          this.init()
        })
      },
      disableExpress(row) {
        row.expressStatus = 0
        saveExpress(row).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功！' })
          this.init()
        })
      },
      deleteExpress(row) {
        this.$confirm('是否确认删除？', '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchDeleteExpress(row.enterpriseExpressId).then(response => {
            if (response.isError) return
            this.$message({ type: 'success', message: '删除成功！' })
            this.init()
          })
        })
      },
      batchEnableExpress() {
        if (this.multipleSelection.length === 0) {
          this.$message({ type: 'error', message: '请先选择快递公司！' })
          return
        }

        const expressIds = this.multipleSelection.map(e => e.enterpriseExpressId)
        batchEnableExpress(expressIds.join(',')).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功！' })
          this.init()
        })
      },
      batchDisableExpress() {
        if (this.multipleSelection.length === 0) {
          this.$message({ type: 'error', message: '请先选择快递公司！' })
          return
        }
        const expressIds = this.multipleSelection.map(e => e.enterpriseExpressId)
        batchDisableExpress(expressIds.join(',')).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功！' })
          this.init()
        })
      },
      batchDeleteExpress() {
        if (this.multipleSelection.length === 0) {
          this.$message({ type: 'error', message: '请先选择快递公司！' })
          return
        }
        const enableExpressList = this.multipleSelection.filter(e => e.expressStatus === 1)
        if (enableExpressList.length > 0) {
          this.$message({ type: 'error', message: '只能删除已停用的快递！' })
          return
        }
        this.$confirm('是否确认删除？', '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const expressIds = this.multipleSelection.map(e => e.enterpriseExpressId)
          batchDeleteExpress(expressIds.join(',')).then(response => {
            if (response.isError) return
            this.$message({ type: 'success', message: '删除成功！' })
            this.init()
          })
        })
      },
      saveExpress() {
        this.$refs['dialogExpress'].validate((valid) => {
          if (valid) {
            this.dialogExpress.enterpriseId = this.getEnterpriseId()
            this.dialogExpress.supplierId = this.getSupplierId()
            saveExpress(this.dialogExpress).then(response => {
              if (response.isError) return
              this.addSysCustomVisible = false
              this.$message({ type: 'success', message: '保存成功！' })
              this.init()
            })
          }
        })
      },
      // 添加系统快递到企业或者供应商快递
      addSysExpress(row) {
        this.saveSysExpress([row.expressId])
      },
      // 批量添加系统快递到企业或者供应商快递
      batchAddExpress() {
        if (this.dialogMultipleSelection.length === 0) {
          this.$message({ type: 'error', message: '请先选择快递公司！' })
          return
        }
        const expressIds = this.dialogMultipleSelection.map(e => e.expressId)
        this.saveSysExpress(expressIds)
      },
      saveSysExpress(expressIds) {
        const supplierId = this.getSupplierId()
        saveSysExpress(this.getEnterpriseId(), expressIds.join(','), supplierId).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功！' })
          this.addSysExpressVisible = false
          this.init()
        })
      },
      getEnterpriseExpressConfig() {
        getEnterpriseExpressConfig(this.getEnterpriseId(), this.getSupplierId()).then(response => {
          if (response.isError) return
          this.expressConfig = Object.assign(this.expressConfig, response.data)
          // if (this.expressConfig.provinceCode) {
          //   this.changeProvince()
          // }
          // if (this.expressConfig.cityCode) {
          //   this.changeCity()
          // }
          if (!this.expressConfig.homeAreaFilter) {
            this.expressConfig.homeAreaFilter = ''
          }
          if (!this.expressConfig.minLogisticsFee) {
            this.expressConfig.minLogisticsFee = ''
          }
        })
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.expressList.length) {
          this.expressList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      selectExpressOutletsAll() {
        if (this.multipleExpressOutletsSelection.length === 0 || this.multipleExpressOutletsSelection.length < this.expressOutletsList.length) {
          this.expressOutletsList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      showDeliveryTemplate(template) {
        this.$router.push({ path: '/order/order/express/delivery-template-detail/index', query: { templateId: template.templateId }})
      },
      onSaveHomeFee() {
        if (!this.homeFeeTemp.homeFee) {
          this.$message.error('请输入物流上门费用')
          return
        }
        if (this.homeFeeTemp.rangeMin * 1 > this.homeFeeTemp.rangeMax * 1) {
          this.$message.error('商品数量区间上限不能小于下限')
          return
        }
        this.homeFee.homeFee = this.homeFeeTemp.homeFee
        this.homeFee.rangeMin = this.homeFeeTemp.rangeMin
        this.homeFee.rangeMax = this.homeFeeTemp.rangeMax
        if (this.homeFee.homeFee * 1 === 0) {
          this.$confirm('物流上门费用为0，是否确认继续保存', { confirmButtonText: '继续保存' })
            .then(_ => {
              this.saveHomeFee()
            })
            .catch(_ => {})
        } else {
          this.saveHomeFee()
        }
      },
      saveHomeFee() {
        saveHomeFee(this.homeFee).then(response => {
          if (response.isError) return
          this.homeFeeVisible = false
          this.listHomeFee()
          this.$message({ type: 'success', message: '保存成功！' })
        })
      },
      tabClick() {
        this.init()
      },
      copyDeliveryTemplate(template) {
        copyDeliveryTemplate(template.templateId).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '复制成功！' })
          this.listTemplate()
        })
      },
      deleteTemplate(template) {
        deleteTemplate(template.templateId).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '删除成功！' })
          this.listTemplate()
        })
      },
      listTemplate() {
        listTemplate({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          this.deliveryTemplateList = response.data
        })
      },
      listHomeFee() {
        listHomeFee({ enterpriseId: this.getEnterpriseId() }).then(response => {
          if (response.isError) return
          this.homeFeeList = response.data
        })
      },
      addHomeFee() {
        this.homeFee = {}
        this.homeFee.enterpriseId = this.getEnterpriseId()
        this.homeFee.sortNo = this.homeFeeList.length
        if (this.homeFeeList.length === 0) {
          this.homeFee.rangeMin = 1
        } else {
          this.homeFee.rangeMin = this.homeFeeList[this.homeFeeList.length - 1].rangeMax * 1 + 1
        }
        this.homeFee.rangeMax = ''
        this.homeFee.homeFee = ''
        this.homeFeeTemp = Object.assign({}, this.homeFee)
        this.homeFeeVisible = true
      },
      editHomeFee(isLast, row) {
        this.homeFee = row
        this.homeFeeTemp = Object.assign({}, row)
        this.homeFeeTemp.disableRangeMax = !isLast
        this.homeFeeVisible = true
      },
      deleteHomeFee(row) {
        deleteHomeFee(row.homeFeeId).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '删除成功！' })
          this.listHomeFee()
        })
      },
      saveEnterpriseExpressConfig() {
        if (!this.expressConfig.homeAreaFilter) {
          this.expressConfig.homeAreaFilter = ''
        }
        if (!this.expressConfig.minLogisticsFee) {
          this.expressConfig.minLogisticsFee = ''
        }
        if (this.activeName === 'logistics' && this.expressConfig.minLogisticsFee * 1 <= 0) {
          this.$message({ type: 'error', message: '最低物流费必须大于0！' })
          return
        }
        saveEnterpriseExpressConfig(this.expressConfig).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功！' })
          this.expressConfigVisible = false
          this.getEnterpriseExpressConfig()
        })
      },
      changeProvince(provinceCode) {
        if (!provinceCode) {
          return
        }
        listCity(provinceCode).then(response => {
          if (response.isError) return
          this.cityList = response.data
        })
      },
      changeCity(cityCode) {
        if (!cityCode) {
          return
        }
        listDistrict(cityCode).then(response => {
          if (response.isError) return
          this.districtList = response.data
        })
      },
      // 保存设置标准面单
      saveStandardFaceSheet() {
        saveStandardFaceSheet(this.faceSheetEntity).then(response => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '设置成功!'
          })
          this.init()
          this.addStandardFaceSheetVisible = false
        })
      },
      doChangeTab() {
        this.setDefaultExpressOutlets()
      },
      // 设置默认网点
      setDefaultExpressOutlets() {
        this.defaultExpressOutletsVisible = true
      },
      // 设置标准面单模板
      addStandardFaceSheet(row) {
        this.addStandardFaceSheetVisible = true
        this.faceSheetEntity.enterpriseExpressId = row.enterpriseExpressId
        if (row.douYinCustomTemplateId) {
          this.faceSheetEntity.douYinStandardTemplateId = row.douYinStandardTemplateId
          this.faceSheetEntity.douYinCustomTemplateId = row.douYinCustomTemplateId
          this.handleTemplateChange(row.douYinCustomTemplateId, 1)
        }
        if (row.pinDuoDuoStandardTemplateId) {
          this.faceSheetEntity.pinDuoDuoStandardTemplateId = row.pinDuoDuoStandardTemplateId
          this.faceSheetEntity.pinDuoDuoCustomTemplateId = row.pinDuoDuoCustomTemplateId
          this.handleTemplateChange(row.pinDuoDuoStandardTemplateId, 4)
        }
        if (row.taoBaoStandardTemplateId) {
          this.faceSheetEntity.taoBaoStandardTemplateId = row.taoBaoStandardTemplateId
          this.faceSheetEntity.taoBaoCustomTemplateId = row.taoBaoCustomTemplateId
          this.handleTemplateChange(row.taoBaoStandardTemplateId, 3)
        }
        this.getExpressFaceSheetList(row.expressCode, row.expressName)
      },
      // 标准模板选择事件
      handleTemplateChange(templateId, platformType) {
        if (!templateId) {
          this.$message({
            type: 'error',
            message: '模板Id不能为空'
          })
          return
        }
        getCustomTemplateListById(templateId).then(response => {
          if (response.isError) return
          const dataList = response.data
          if (platformType === 1) {
            this.douYinCustomList = dataList
          } else if (platformType === 3) {
            this.taoBaoCustomList = dataList
          } else if (platformType === 4) {
            this.pinDuoDuoCustomList = dataList
          }
        })
      },
      // 查询物流标准面单列表
      getExpressFaceSheetList(expressCode, expressName) {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          supplierId: this.getSupplierId(),
          expressCode: expressCode,
          templateDataType: 1
        }
        this.douYinStandardList = []
        this.douYinCustomList = []
        this.taoBaoStandardList = []
        this.taoBaoCustomList = []
        this.pinDuoDuoStandardList = []
        this.pinDuoDuoCustomList = []
        getPlatformTemplateList(params).then(response => {
          if (response.isError) return
          const dataList = response.data
          dataList.forEach(e => {
            const dtoList = e.dtoList
            const platformType = e.platformType
            dtoList.forEach(dto => {
              dto.templateName = dto.templateName + '(' + expressName + ')'
            })
            if (platformType === 1) {
              this.douYinStandardList = dtoList
            } else if (platformType === 3) {
              this.taoBaoStandardList = dtoList
            } else if (platformType === 4) {
              this.pinDuoDuoStandardList = dtoList
            }
          })
        })
      },
      // 编辑快递鸟参数
      editKdnConfig(row) {
        this.kdnConfigVisible = true
        if (this.$refs['kdnConfigForm']) {
          this.$refs['kdnConfigForm'].resetFields()
        }
        this.kdnConfigForm.enterpriseExpressId = row.enterpriseExpressId
        getKdnConfig(row.enterpriseExpressId).then(response => {
          if (response.isError) return
          Object.assign(this.kdnConfigForm, response.data)
        })
      },
      // 保存快递鸟参数
      saveKdnConfig() {
        saveKdnConfig(this.kdnConfigForm).then(response => {
          if (response.isError) return
          this.kdnConfigVisible = false
        })
      }
    }
  }
</script>
